package cn.bxshey.resourceSharing.controller;



import cn.bxshey.resourceSharing.dto.login.EnrollDto;
import cn.bxshey.resourceSharing.dto.user.UpdateUserDTO;
import cn.bxshey.resourceSharing.entity.R;
import cn.bxshey.resourceSharing.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.bxshey.resourceSharing.entity.User;
import cn.bxshey.resourceSharing.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Objects;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2023-12-16 17:54:45
 */
@RestController
@RequestMapping("user")
public class UserController{
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;


    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param user 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R<?> selectAll(Page<User> page, User user) {
        return R.success(this.userService.page(page, new QueryWrapper<>(user)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R<?> selectOne(@PathVariable Serializable id) {
        return R.success(this.userService.getById(id));
    }

    /**
     * 用户注册
     *
     */
    @PostMapping("/enroll")
    public R<?> enroll(@RequestBody EnrollDto enrollDto) {
        return R.success( userService.enroll(enrollDto));
    }

    /**
     * 修改数据
     *
     * @param dto 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R<?> update(@RequestHeader("AUTHORIZATION_TOKEN") String token,@RequestBody UpdateUserDTO dto) {
        User info = JwtUtils.checkToken(token);
        if(Objects.isNull(info)){
            return R.error("登录验证或已失效");
        }
        return R.success(userService.update(dto,info.getId()));
    }

    /**
     * 删除数据
     *
     *
     * @return 删除结果
     */
    @DeleteMapping
    public R<?> delete(@RequestHeader("AUTHORIZATION_TOKEN") String token) {
        User info = JwtUtils.checkToken(token);
        if(Objects.isNull(info)){
            return R.error("登录验证或已失效");
        }
        return R.success(this.userService.removeById(info.getId()));
    }
}

